import sys
import tkinter as tk
from tkinter import messagebox
import requests
from threading import Thread
import time

def fetch_advice(advice_type):
    url = "http://47.108.221.119:5000/" + ("dietAdvice" if advice_type == "diet" else "exerciseAdvice")
    payload = {
        "time": current_time,
        "machine_id": machine_id
    }
    
    try:
        response = requests.post(url, json=payload, timeout=9000)
        if response.status_code == 200:
            return response.json().get("advice", "未获取到建议")
        else:
            return f"请求失败，状态码：{response.status_code}"
    except requests.Timeout:
        return "响应超时"
    except Exception as e:
        return str(e)

def update_text_box(text_box, message):
    text_box.delete(1.0, tk.END)
    text_box.insert(tk.END, message)

def get_advice(advice_type, text_box):
    update_text_box(text_box, "正在处理...")
    def task():
        result = fetch_advice(advice_type)
        root.after(0, lambda: update_text_box(text_box, result))
    
    thread = Thread(target=task)
    thread.start()

# 获取machine_id和当前时间
machine_id = sys.argv[1] if len(sys.argv) > 1 else "未提供机器码"
current_time = time.strftime('%Y%m%d%H%M%S', time.localtime())

# 创建主窗口
root = tk.Tk()
root.title("健康建议")

# 创建并放置组件
frame = tk.Frame(root)
frame.pack(padx=10, pady=10)

tk.Button(frame, text="获取饮食建议", command=lambda: get_advice("diet", advice_box_diet)).grid(row=0, column=0, padx=5, pady=5)
tk.Button(frame, text="获取运动建议", command=lambda: get_advice("exercise", advice_box_exercise)).grid(row=0, column=1, padx=5, pady=5)

advice_box_diet = tk.Text(frame, width=40, height=10)
advice_box_diet.grid(row=1, column=0, padx=5, pady=5)

advice_box_exercise = tk.Text(frame, width=40, height=10)
advice_box_exercise.grid(row=1, column=1, padx=5, pady=5)

# 开始主循环
root.mainloop()